package cn.bugDance.infrastructure.persistent.repository;

import cn.bugDance.domain.security.model.entity.UserIdOpenIdEntity;
import cn.bugDance.domain.security.repository.ISecurityRepository;
import cn.bugDance.infrastructure.persistent.dao.IUserIdOpenIdDao;
import cn.bugDance.infrastructure.persistent.po.UserIdOpenId;
import cn.bugDance.infrastructure.persistent.redis.IRedisService;
import cn.bugDance.types.common.Constants;
import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;

@Component
public class SecurityRepository implements ISecurityRepository {

    @Resource
    private IUserIdOpenIdDao userIdOpenIdDao;
    @Resource
    private IDBRouterStrategy dbRouter;
    @Resource
    private IRedisService redisService;

    @Override
    public UserIdOpenIdEntity queryUserIdOpenIdEntityByOpenId(String openId) {
        try{
            dbRouter.doRouter(openId);
            UserIdOpenId userIdOpenId = userIdOpenIdDao.getUserIdOpenId(openId);
            if(null == userIdOpenId) return null;
            UserIdOpenIdEntity userIdOpenIdEntity = new UserIdOpenIdEntity();
            userIdOpenIdEntity.setUserId(userIdOpenId.getUserId());
            userIdOpenIdEntity.setOpenId(userIdOpenId.getOpenId());
            return userIdOpenIdEntity;
        }finally {
            dbRouter.clear();
        }
    }

    @Override
    public void saveJwtToken(String ticket, String jwtToken) {
        String cacheKey = Constants.Redis.TICKET_TOKEN + ticket;
        redisService.setValue(cacheKey, jwtToken, (long) 60 * 60 * 1000);
    }

    @Override
    public String checkJwtToken(String ticket) {
        String cacheKey = Constants.Redis.TICKET_TOKEN + ticket;
        return redisService.getValue(cacheKey);
    }
}
